<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item>
        <el-input v-model="dataForm.key" placeholder="参数名" clearable @input="getDataList()"></el-input>
      </el-form-item>
      <el-form-item>
        <el-upload
          class="upload"
          action
          :multiple="false"
          :show-file-list="false"
          accept="csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          :http-request="httpRequest"
        >
          <el-button type="primary">批量添加学生</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <!-- <el-button @click="getDataList()">查询</el-button> -->
        <el-button
          v-if="isAuth('department:sys:save')"
          type="primary"
          @click="addOrUpdateHandle()"
        >新增</el-button>
        <!-- <el-button
          v-if="isAuth('department:sys:delete')"
          type="danger"
          @click="deleteHandle()"
          :disabled="dataListSelections.length <= 0"
        >批量删除</el-button>-->
      </el-form-item>
    </el-form>
    <el-table :data="dataList" border v-loading="dataListLoading" style="width: 100%">
      <!-- <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column> -->
      <el-table-column type="expand" align="center">
        <template slot-scope="props">
          <el-table
            :data="props.row.students"
            style="width: 100%"
            max-height="250"
            v-if="props.row.students != null"
          >
            <el-table-column prop="stuNo" header-align="center" align="center" label="学号"></el-table-column>
            <el-table-column prop="stuName" header-align="center" align="center" label="姓名"></el-table-column>
            <el-table-column prop="mobili" header-align="center" align="center" label="手机号"></el-table-column>
            <el-table-column prop="email" header-align="center" align="center" label="邮箱"></el-table-column>
            <el-table-column align="center" header-align="center" label="状态">
              <template slot-scope="scope">
                <el-switch
                  style="display: block"
                  v-model="scope.row.status"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  active-text="正常"
                  inactive-text="禁用"
                  :active-value="1"
                  :inactive-value="0"
                  @change="changeStuStatus(scope.row)"
                ></el-switch>
              </template>
            </el-table-column>
            <el-table-column
              header-align="center"
              align="center"
              width="200"
              label="操作"
              fixed="right"
            >
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="updateStu(scope.row,props.row.id)">修改</el-button>
                <el-button type="text" size="small" @click="deleteStu(scope.row,props.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-table style="width: 100%" max-height="250" v-else></el-table>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="id" header-align="center" align="center" label="班级编号"></el-table-column> -->
      <el-table-column prop="departmentName" header-align="center" align="center" label="系部名称"></el-table-column>
      <el-table-column prop="name" header-align="center" align="center" label="班级名称"></el-table-column>
      <el-table-column prop="studentCount" header-align="center" align="center" label="学生人数"></el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        width="200"
        label="操作"
        v-if="isAuth('department:sys:update') || isAuth('department:sys:delete')"
      >
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="addStudent(scope.row.id)">添加学生</el-button>
          <el-button
            type="text"
            size="small"
            @click="addOrUpdateHandle(scope.row.id)"
            v-if="isAuth('department:sys:update')"
          >修改</el-button>
          <el-button
            type="text"
            size="small"
            @click="deleteHandle(scope.row.id)"
            v-if="isAuth('department:sys:delete')"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :title="addStu === 'add' ? '添加学生':'修改学生'" :visible.sync="dialogVisible" width="35%">
      <el-form
        :model="dataForm"
        :rules="dataRule"
        ref="dataForm"
        @keyup.enter.native="dataFormSubmit()"
        label-width="80px"
      >
        <el-form-item label="学号" prop="stuNo">
          <el-input v-model="dataForm.stuNo" placeholder="请输入学号" :disabled="addStu === 'update'"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="stuName">
          <el-input v-model="dataForm.stuName" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item
          label="密码"
          prop="password"
          :class="{ 'is-required': !dataForm.stuNo }"
          v-if="addStu === 'update'"
        >
          <el-input v-model="dataForm.password" type="password" placeholder="密码"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submitAddStudent">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="批量添加" :visible.sync="batchAddStuDialogVisible" width="35%">
      <el-select
        v-model="batchAddStudentClassId"
        filterable
        placeholder="请选择班级"
        style="margin-bottom:10px"
      >
        <el-option
          v-for="item in selectClass"
          :key="item.classId"
          :label="item.className"
          :value="item.classId"
        ></el-option>
      </el-select>
      <el-table :data="batchAddStuTableData" border style="width: 100%">
        <el-table-column prop="stuNo" header-align="center" align="center" label="学号"></el-table-column>
        <el-table-column prop="stuName" header-align="center" align="center" label="姓名"></el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="batchAddStuDialogVisible=false">取 消</el-button>
        <el-button type="primary" @click="batchAddStudent">确 定</el-button>
      </span>
    </el-dialog>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
  </div>
</template>

<script>
import AddOrUpdate from './class-add-or-update'
import XLSX from 'xlsx'  // 引入xlsx

export default {
  data () {
    return {
      batchAddStudentClassId: null,
      selectClass: [],
      batchAddStuDialogVisible: false,
      batchAddStuTableData: [],
      dataForm: {
        stuNo: null,
        stuName: null,
        password: null,
        key: ''
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      dialogVisible: false,
      addStu: '',
      dataRule: {
        stuNo: [
          { required: true, message: '学号不能为空', trigger: 'blur' }
        ],
        stuName: [
          { required: true, message: '姓名不能为空', trigger: 'blur' }
        ]
      },
      classId: null
    }
  },
  components: {
    AddOrUpdate,
    XLSX
  },
  activated () {
    this.getDataList()
  },
  methods: {
    getStudentList (classId) {
      this.$http({
        url: this.$http.adornUrl('/workmanagement/student/getByClassId'),
        method: 'get',
        params: this.$http.adornParams({
          classId
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList.forEach(item => {
            if (item.id === classId) {
              item.students = data.students
            }
          })
        } else {
          this.dataList.forEach(item => {
            if (item.id === classId) {
              item.students = []
            }
          })
        }
      })
    },
    batchAddStudent () {
      this.$http({
        url: this.$http.adornUrl(`/workmanagement/student/batchAddStudent`),
        method: 'post',
        data: this.$http.adornData({
          'classId': this.batchAddStudentClassId,
          'students': this.batchAddStuTableData
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.batchAddStuDialogVisible = false
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.getDataList()
            }
          })
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    httpRequest (e) {
      this.batchAddStudentClassId = null
      this.batchAddStuTableData = []
      let file = e.file // 文件信息
      if (!file) {
        // 没有文件
        return false
      } else if (!/\.(xls|xlsx)$/.test(file.name.toLowerCase())) {
        // 格式根据自己需求定义
        this.$message.error('上传格式不正确，请上传xls或者xlsx格式')
        return false
      }

      const fileReader = new FileReader()

      fileReader.onload = ev => {
        try {
          const data = ev.target.result
          const workbook = XLSX.read(data, {
            type: 'binary' // 以字符编码的方式解析
          })
          const exlname = workbook.SheetNames[0] // 取第一张表
          let exl = XLSX.utils.sheet_to_json(workbook.Sheets[exlname]) // 生成json表格内容
          let dataList = []
          exl.forEach(item => {
            dataList.push({ stuNo: item['学号'], stuName: item['姓名'] })
          })
          this.batchAddStuTableData = dataList
          this.batchAddStuDialogVisible = true
        } catch (e) {
          console.log('出错了：：')
          return false
        }
      }
      fileReader.readAsBinaryString(file)
    },
    closeDialog () {
      this.dialogVisible = false
      this.$refs['dataForm'].resetFields()
    },
    deleteStu (row, classId) {
      this.$confirm(`确定从班级中移除${row.stuName}?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl(`/workmanagement/student/deleteStudent`),
          method: 'delete',
          params: this.$http.adornParams({
            'stuNo': row.stuNo,
            'classId': classId
          })
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getStudentList(classId)
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      })
    },
    updateStu (row, classId) {
      let { stuNo, stuName } = row
      this.dataForm.stuNo = stuNo
      this.dataForm.stuName = stuName
      this.classId = classId
      this.dialogVisible = true
      this.addStu = 'update'
    },
    changeStuStatus (row) {
      let { stuNo, status } = row
      this.$http({
        url: this.$http.adornUrl('/workmanagement/class/changeStuStatus'),
        method: 'get',
        params: this.$http.adornParams({
          stuNo,
          status
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    submitAddStudent () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/workmanagement/student/${this.addStu === 'add' ? 'addStudent' : 'updateStudent'}`),
            method: 'post',
            data: this.$http.adornData({
              'classId': this.classId,
              'stuNo': this.dataForm.stuNo,
              'stuName': this.dataForm.stuName,
              'password': this.dataForm.password
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dialogVisible = false
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.classId = null
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    },
    addStudent (classId) {
      this.classId = classId
      this.addStu = 'add'
      this.dialogVisible = true
    },
    // 获取数据列表
    getDataList () {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/workmanagement/class/list'),
        method: 'get',
        params: this.$http.adornParams({
          'page': this.pageIndex,
          'limit': this.pageSize,
          'key': this.dataForm.key
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list
          this.totalPage = data.page.totalCount
          this.dataList.forEach(item => {
            this.selectClass.push({ classId: item.id, className: item.name })
          })
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })
    },
    // 每页数
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 多选
    selectionChangeHandle (val) {
      this.dataListSelections = val
    },
    // 新增 / 修改
    addOrUpdateHandle (id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id)
      })
    },
    // 删除
    deleteHandle (id) {
      var ids = id ? [id] : this.dataListSelections.map(item => {
        return item.id
      })
      this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/workmanagement/class/delete'),
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      })
    }
  }
}
</script>
